import Vue from 'vue'

function checkPermission(el, binding, vnode, store) {
  const {
    value
  } = binding
  const userType = store.state.user.authUser.usertype || 0;
  const roles = userType === 1
    ? ['personal']
    : userType === 2
    ? ['company']
    : ['guest'];

  if (value && value instanceof Array) {
    if (value.length > 0) {
      const permissionRoles = value

      const hasPermission = roles.some(role => {
        return permissionRoles.includes(role)
      })

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  } else {
    throw new Error('need roles! Like v-permission="[\'admin\',\'editor\']"')
  }
}
export default ({
  store,
  redirect
}) => {
  Vue.directive('permission', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: (el, binding, vnode) => {
      checkPermission(el, binding, vnode, store)
    },
    update: (el, binding, vnode) => {
      checkPermission(el, binding, vnode, store)
    },
  })
}
